package com.eascs.admin.o2o.applyAssessment.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.applyAssessment.entity.ApplyAssessmentEntity;
import com.eascs.admin.o2o.applyAssessment.entity.ApplyAssessmentForm;
import com.eascs.admin.o2o.applyAssessment.entity.ApplyAssessmentVo;
import com.eascs.admin.o2o.applyAssessment.service.ApplyAssessmentService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.submitted.vo.O2oLoanSubmittedVo;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.common.util.StringUtil;
import com.eascs.file.FileTypeConstants;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.sys.SysUser;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.EmployeeService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@RestController
@RequestMapping("/rApplyAssessment")
public class ApplyAssessmentRestController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(ApplyAssessmentRestController.class);

	@Reference
	SysOrgService sysOrgService;
	@Autowired
	ApplyAssessmentService service;
	@Autowired
	private BaseUtils baseUtils;
	@Reference
	EmployeeService employeeDubboService;
	@Reference
	SequenceService sequenceService;

	/**
	 * 新增提前进入考核期功能页面:跳转
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/newApply")
	public BaseRestResult<String> newApply() {
		// User user = UserHolder.getUser();
		// List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		// ViewContext.put("ActOrgEntitys", orgProvince);
		// ViewContext.put("currentUser", user.getCname());
		// ViewContext.put("currentUserCode", user.getNo());
		return HtmlRestResult.popHtmlFragment("/applyAssessment/new_apply");
	}

	/**
	 * 新增提前进入考核期功能页面:保存
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/newApply_add")
	public BaseRestResult<?> newApplyAdd(ApplyAssessmentForm form) {// 用form代替entity接收表单参数
																	// ,form中多增加一个是否启动流程的标记值type
		// ====添加非空判断

		//
		if (form != null) {
			if (StringUtils.isEmpty(form.getName())) {
				return BaseRestResult.warn("姓名为空，请输入!");
			}
			if (StringUtils.isEmpty(form.getPosition())) {
				return BaseRestResult.warn("职位为空，请输入!");
			}
			if (StringUtils.isEmpty(form.getTeam())) {
				return BaseRestResult.warn("所属团队为空，请输入!");
			}
			if (StringUtils.isEmpty(form.getApplyAssessmentExplain())) {
				return BaseRestResult.warn("提前进入考核说明为空，请输入!");
			}
			//
			// SysUser user = employeeDubboService.
			SysUser user = employeeDubboService.getSysUserByNo(form.getEmployeeNo());// user中有跨库查询所需的数据
			String provinceId = user.getProvinceCode();

			List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(provinceId);
			if (actOrgList == null || actOrgList.size() == 0) {
				return BaseRestResult.warn("找不到经办平台，请联系管理员");
			}
			ActOrgEntity actOrgEntity = null;
			for (ActOrgEntity org : actOrgList) {
				if (org.getOrgLevel() == 4) {
					actOrgEntity = org;
					break;
				}
			}
			if (actOrgEntity == null) {
				return BaseRestResult.warn("找不到经办平台对应的省区金融部，请联系管理员");
			}
			String billCode = sequenceService.getSeq("O2O_TQKH_NO", 5, "TQKH");// 流程单号序列化输出(格式化输出,返回序列号)
			// ==============================================================================================
			ApplyAssessmentEntity entity = new ApplyAssessmentEntity();
			// 以下数据从SysUser类的 user中取出
			entity.setProvinceCode(provinceId);// 设置省区code
			entity.setWfStatus(-1);// 设置流程状态为新建 流程状态：-1 新建, 0 审核通过, 2 审核中, 3 驳回
			entity.setProvinceName(user.getProvinceName());// 设置省区name
			entity.setHiredate(user.getJoinDate());// 设置入职时间
			entity.setBillCode(billCode);// 设置流程单号
			entity.setOrgId(actOrgEntity.getUnitNo());// 设置平台id
			entity.setOrgName(actOrgEntity.getOrgName());// 设置平台name

			// 表单中传递参数
			entity.setName(form.getName());
			entity.setEmployeeNo(form.getEmployeeNo());
			entity.setPosition(form.getPosition());
			entity.setTeam(form.getTeam());
			entity.setApplyAssessmentExplain(form.getApplyAssessmentExplain());

			// 保存时需手动保存的信息
			entity.setCreateDate(new Date());// 设置创建时间
			entity.setCreaterId(UserHolder.getUser().getNo());// 设置创建人id
			entity.setCreaterName(UserHolder.getUser().getCname());// 设置创建人name
			entity.setStatus(1);// 设置状态: 1正常,2删除

			int count = service.newApplySave(entity);
			if (StringUtil.isNotBlank(form.getType()) && count > 0) {
				// if("true".equals(applyStartFlow(entity)))//如果流程启动成功,再写个流程启动的方法
				// }
				ModelResult<Boolean> startUp = service.startUp(entity);
				if (startUp.isSuccess() && startUp.getModel()) {
					return BaseRestResult.info("保存并流程启动成功").andRedirect(UrlHelper.build("/applyAssessment/list"));
				} else {
					return BaseRestResult.warn("保存成功,启动失败,原因:" + startUp.getErrMsg())
							.andRedirect(UrlHelper.build("/applyAssessment/list"));
				}
			} else if (count > 0) {
				return BaseRestResult.info("保存成功").andRedirect(UrlHelper.build("/applyAssessment/list"));
			} else {
				logger.info("保存失败");
				return BaseRestResult.warn("保存失败");
			}
		}
		return BaseRestResult.error("保存失败,entity为null");

	}

	@RequestMapping("/delete")
	public BaseRestResult<String> deleteApply(String id) {
		// ApplyAssessmentEntity applyEntity = service.getEntityById(id);
		// 权限验证
		//
		if (StringUtil.isEmpty(id)) {
			return BaseRestResult.warn("id为空，无法删除！");
		} else {
			ModelResult<Boolean> deleteResult = service.deleteApplyService(id);
			if (deleteResult.isSuccess() && deleteResult.getModel()) {
				return BaseRestResult.info("删除成功").andRedirect(UrlHelper.build("/applyAssessment/list"));
			} else {
				return BaseRestResult.warn(deleteResult.getErrMsg());
			}
		}
	}

	@RequestMapping("/edit")
	public BaseRestResult<String> editApply(String id) {
		ApplyAssessmentEntity applyEntity = service.getEntityById(id);
		ViewContext.put("entity", applyEntity);
		return HtmlRestResult.popHtmlFragment("/applyAssessment/apply_edit");
	}

	@RequestMapping("/edit_save")
	public BaseRestResult<?> updateApply(ApplyAssessmentForm vo) {
		if (vo != null) {
			if (StringUtils.isEmpty(vo.getName())) {
				return BaseRestResult.warn("姓名为空，请输入!");
			}
			if (StringUtils.isEmpty(vo.getPosition())) {
				return BaseRestResult.warn("职位为空，请输入!");
			}
			if (StringUtils.isEmpty(vo.getTeam())) {
				return BaseRestResult.warn("所属团队为空，请输入!");
			}
			if (StringUtils.isEmpty(vo.getApplyAssessmentExplain())) {
				return BaseRestResult.warn("提前进入考核说明为空，请输入!");
			}
			SysUser user = employeeDubboService.getSysUserByNo(vo.getEmployeeNo());// user中有跨库查询所需的数据
			String provinceId = user.getProvinceCode();

			List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(provinceId);
			if (actOrgList == null || actOrgList.size() == 0) {
				return BaseRestResult.warn("找不到经办平台，请联系管理员");
			}
			ActOrgEntity actOrgEntity = null;
			for (ActOrgEntity org : actOrgList) {
				if (org.getOrgLevel() == 4) {
					actOrgEntity = org;
					break;
				}
			}
			if (actOrgEntity == null) {
				return BaseRestResult.warn("找不到经办平台对应的省区金融部，请联系管理员");
			}
			// -------
			ApplyAssessmentEntity entity = service.getEntityById(vo.getId());
			entity.setName(vo.getName());
			entity.setEmployeeNo(vo.getEmployeeNo());
			entity.setPosition(vo.getPosition());
			entity.setTeam(vo.getTeam());
			entity.setApplyAssessmentExplain(vo.getApplyAssessmentExplain());
			//
			entity.setProvinceCode(provinceId);// 设置省区code
			entity.setProvinceName(user.getProvinceName());// 设置省区name
			entity.setHiredate(user.getJoinDate());// 设置入职时间
			entity.setOrgId(actOrgEntity.getUnitNo());// 设置平台id
			entity.setOrgName(actOrgEntity.getOrgName());// 设置平台name
			// ---
			entity.setUpdateDate(new Date());
			entity.setUpdatorId(UserHolder.getUser().getNo());
			entity.setUpdatorName(UserHolder.getUser().getCname());
			//
			//
			ModelResult<Boolean> updateResult = service.updateApply(entity);// 更新
			//如果 点击保存并启动流程按钮 且 编辑内容更新成功
			if (StringUtil.isNotBlank(vo.getType()) && (updateResult.isSuccess() && updateResult.getModel())) {
				ModelResult<Boolean> startUp = service.startUp(entity);
				if (startUp.isSuccess() && startUp.getModel()) {// 如果启动流程成功
					return BaseRestResult.info("保存并流程启动成功").andRedirect(UrlHelper.build("/applyAssessment/list"));
				} else {
					return BaseRestResult.warn("保存成功,启动失败,原因:" + startUp.getErrMsg())
							.andRedirect(UrlHelper.build("/applyAssessment/list"));
				}
			} else if (updateResult.isSuccess() && updateResult.getModel()) {// 否则如果只是更新已成功
				return BaseRestResult.info("保存成功").andRedirect(UrlHelper.build("/applyAssessment/list"));
			} else {
				logger.info("保存失败");
				return BaseRestResult.warn("保存失败");
			}
		}

		return BaseRestResult.error("保存失败,entity为null");

	}

	/**
	 * 单据详情、待办详情：申请信息、审核记录
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/detail")
	// public HtmlRestResult detailInfo(String id){
	public BaseRestResult<String> detailInfo(String id) {
		// ApplyAssessmentEntity applyEntity = service.queryById(id);
		ApplyAssessmentEntity applyEntity = service.getEntityById(id);
		ViewContext.put("vo", applyEntity);
		// List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		// ViewContext.put("ActOrgEntitys", orgProvince);
		return new HtmlRestResult("/applyAssessment/details");
	}

	/**
	 * 启动流程
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/applyStartFlow")
	public BaseRestResult<String> applyStartFlow(ApplyAssessmentEntity applyEntity) {
		// 权限校验 后面会用到entity
		// ApplyAssessmentEntity applyEntity = service.getEntityById(id);
		// ModelResult<Boolean> checkRole = isCurrentRole(applyEntity,
		// "startFlow");
		// if (!checkRole.getModel()) {
		// return BaseRestResult.warn(checkRole.getErrMsg());
		// }
		// ---
		ModelResult<Boolean> startUp = service.startUp(applyEntity);
		if (startUp.isSuccess() && startUp.getModel()) {
			return BaseRestResult.info("流程启动成功").andRedirect(UrlHelper.build("/applyAssessment/list"));
		} else {
			return BaseRestResult.warn(startUp.getErrMsg());
		}

	}

	@RequestMapping("/view_flow")
	public BaseRestResult<String> viewFlow(String approvalStatus, String referId, String nodeAuditorId) {
		// --------------------------------------------------------------"TQKH"是否写对了
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId, "TQKH");// 审批代办列表详情URL
		ApplyAssessmentEntity applyEntity = service.getEntityById(referId);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(referId, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("vo", applyEntity);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("parameter", referId);
		// ViewContext.put("currentUser", applyEntity.getUpdatorName());//经办人??
		// .................???
		ViewContext.put("approvalStatus", approvalStatus);// 流程经办状态是待办/已办/已发起，待办状态才显示审批栏

		// --------------------------------------
		// --------------------------------------
		return HtmlRestResult.popHtmlFragment("/applyAssessment/apply_flow");
	}

	/**
	 * 动态悬浮按钮
	 */
	@RequestMapping("/buttons")
	public BaseRestResult<String> buttons(String id) {
		List<Button> buttons = new ArrayList<>();
		// ------------------------------------三个按钮的permissionCode待改
		Button startUpBtn = ButtonHelper.createAjaxButton("启动流程", "/rApplyAssessment/applyStartFlow?id=" + id,
				"startApplyFlow");
		Button editBtn = ButtonHelper.createAjaxButton("编辑", "/rApplyAssessment/edit?id=" + id, "editApply");
		Button deleteBtn = ButtonHelper.createAjaxConfirmButton("删除", "/rApplyAssessment/delete?id=" + id, "delApply");
		deleteBtn.setConfirmMessage("数据删除后不可见，确认删除吗？");
		buttons.add(startUpBtn);
		buttons.add(editBtn);
		buttons.add(deleteBtn);
		ViewContext.put("applyButtons", buttons);
		return new HtmlRestResult("applyAssessment/buttons");
	}
}
